import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:sui_shou_pai/Utils/storage_util.dart';
import 'package:sui_shou_pai/module/color.dart';
import 'package:sui_shou_pai/module/effect.dart';
import 'package:sui_shou_pai/my/init_info/init_information.dart';
import 'package:sui_shou_pai/my/my_comment.dart';
import 'package:sui_shou_pai/my/my_likes.dart';
import 'package:sui_shou_pai/my/photo_record.dart';
import 'package:sui_shou_pai/my/setting.dart';
import 'package:sui_shou_pai/my/show_big_photo.dart';
import 'package:sui_shou_pai/network/http_request.dart';
import 'package:sui_shou_pai/record/image_widget.dart';

import 'bottom_sheet_widget.dart';

class MyPage extends StatefulWidget {
  MyPage({Key key}) : super(key: key);

  @override
  _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  String _headIcon = "";
  String name = "";
  String employeeId = "";
  String role;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _headIcon = InitInformation.avatar;
    name = InitInformation.name;
    employeeId = InitInformation.employeeId;
    role = InitInformation.role;
  }

  Future<Null> _handleRefresh() async {
    // 模拟数据的延迟加载
    await Future.delayed(Duration(seconds: 1), () {
      InitInformation.initInform();
      setState(() {
        _headIcon = InitInformation.avatar;
        print(_headIcon);
        name = InitInformation.name;
        employeeId = InitInformation.employeeId;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: ConstrainedBox(
          constraints: BoxConstraints.expand(),
          child: Stack(
            children: <Widget>[
              Positioned(
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  height: 270,
                  child: Image.asset(
                    'assets/images/bgphoto.jpg',
                    fit: BoxFit.cover,
                  ),
                  // child: Image.asset("assets/images/bgphoto.jpg"),
                ),
              ),
              Positioned(
                top: 240.0,
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  height: MediaQuery.of(context).size.height,
                  margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
                  decoration: BoxDecoration(
                    borderRadius: borderRadiusOnlyLeftTop24(),
                    color: Colors.white,
                  ),
                  child: Container(
                    child: Column(
                      children: [
                        Container(
                            margin: EdgeInsets.only(top: 16),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  name,
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      decoration: null,
                                      fontSize: 30),
                                ),
                                Text(
                                  "工号：$employeeId",
                                  style: TextStyle(
                                      color: Colors.grey,
                                      decoration: null,
                                      fontSize: 15),
                                ),
                              ],
                            )),
                        Expanded(
                          child: Container(
                            child: RefreshIndicator(
                              child: ListView(
                                padding: EdgeInsets.symmetric(
                                    horizontal: 12, vertical: 8),
                                children: [
                                  _myComment(),
                                  _myLikes(),
                                  _photoRecords(),
                                  _setting(),
                                ],
                              ),
                              onRefresh: _handleRefresh,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              Positioned(
                top: 224,
                left: 40,
                child: _headIconBuilder(),
              )
            ],
          )),
    );
  }

  Widget _headIconBuilder() {
    return GestureDetector(
      onTap: () {
        showDialog(
            barrierDismissible: true, //是否点击空白区域关闭对话框,默认为true，可以关闭
            context: context,
            // barrierColor: Colors.transparent,
            builder: (BuildContext context) {
              var list = [];
              list.add('查看头像');
              list.add('从相册选择照片');
              list.add('拍照');
              return BottomSheetWidget(
                list: list,
                onItemClickListener: (index) async {
                  Navigator.pop(context);
                  if (index == 0) {
                    showBigPhoto();
                  } else if (index == 1) {
                    pickImage();
                  } else {
                    takePhoto();
                  }
                },
              );
            });
      },
      child: Container(
        alignment: Alignment.centerLeft,
        child: Container(
          constraints: BoxConstraints.expand(
            width: 100.0,
            height: 100.0,
          ),
          decoration: new BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(50)),
            boxShadow: [
              BoxShadow(
                color: Colors.grey,
                offset: Offset(0.0, 2.0),
                blurRadius: 6.0,
              )
              // shadowOffsetY2()
            ],
          ),
          child: ClipOval(child: ImageWidget(url: _headIcon, w: 100, h: 100)
              // Image.network(_headIcon,
              //     width: 100, height: 100, fit: BoxFit.cover),
              ),
        ),
      ),
    );
  }

  Widget _myComment() {
    return Container(
      padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
      child: GestureDetector(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => MyComment()),
          );
        },
        child: Container(
          height: 40,
          margin: EdgeInsets.fromLTRB(10, 20, 10, 0),
          padding: EdgeInsets.only(bottom: 10),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("我的评论", style: TextStyle(fontSize: 18)),
              Icon(
                Icons.comment,
                color: greyCCCCCC,
              ),
            ],
          ),
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(width: 1, color: Color(0xffe5e5e5)))),
        ),
      ),
    );
  }

  Widget _myLikes() {
    return Container(
      padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
      child: GestureDetector(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => MyLike()),
          );
        },
        child: Container(
          height: 40,
          margin: EdgeInsets.fromLTRB(10, 20, 10, 0),
          padding: EdgeInsets.only(bottom: 10),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("我的点赞", style: TextStyle(fontSize: 18)),
              Icon(
                Icons.thumb_up,
                color: greyCCCCCC,
              ),
            ],
          ),
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(width: 1, color: Color(0xffe5e5e5)))),
        ),
      ),
    );
  }

  Widget _photoRecords() {
    if (role == "boss") {
      return Container(
        padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
        child: GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => MyPhotoRecord()),
            );
          },
          child: Container(
            height: 40,
            margin: EdgeInsets.fromLTRB(10, 20, 10, 0),
            padding: EdgeInsets.only(bottom: 10),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text("拍照记录", style: TextStyle(fontSize: 18)),
                Icon(
                  Icons.photo_camera,
                  color: greyCCCCCC,
                ),
              ],
            ),
            decoration: BoxDecoration(
                border: Border(
                    bottom: BorderSide(width: 1, color: Color(0xffe5e5e5)))),
          ),
        ),
      );
    } else {
      return SizedBox();
    }
  }

  Widget _setting() {
    return Container(
      padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
      child: GestureDetector(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => Setting()),
          );
        },
        child: Container(
          height: 40,
          margin: EdgeInsets.fromLTRB(10, 20, 10, 0),
          padding: EdgeInsets.only(bottom: 10),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("设置", style: TextStyle(fontSize: 18)),
              Icon(
                Icons.settings,
                color: greyCCCCCC,
              ),
            ],
          ),
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(width: 1, color: Color(0xffe5e5e5)))),
        ),
      ),
    );
  }

  void showBigPhoto() {
    Navigator.of(context).push(BigPhoto(Image.network(_headIcon)));
  }

  void pickImage() {
    ImagePicker.platform
        .pickImage(source: ImageSource.gallery, imageQuality: 50)
        .then(
          (value) => {
            setState(
              () {
                savaAvatar(value.path);
              },
            ),
          },
        );
  }

  void takePhoto() {
    ImagePicker.platform
        .pickImage(source: ImageSource.camera, imageQuality: 50)
        .then(
          (value) => {
            setState(
              () {
                savaAvatar(value.path);
              },
            ),
          },
        );
  }

  savaAvatar(imgPath) async {
    MultipartFile avatar =
        MultipartFile.fromFileSync(imgPath, filename: "avatar.png");

    var formData = FormData.fromMap({
      "file": avatar,
      "employeeId": "100111",
    });
    HttpRequest.request("/employee/saveAvatar",
            method: "post",
            data: formData,
            token: await StorageUtil.getStringItem("token"))
        .then((value) {
      if (value.data["code"] == 200) {
        setState(() {
          _headIcon = value.data["result"];
        });
      } else {
        Fluttertoast.showToast(msg: "头像保存失败");
      }
    });
  }
}
